import { Directive, ElementRef, Input } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";

@Directive({
    selector: '[bulletChart]'
})
export class BulletChartDirective {
    private chart: any;
    private _chartData: number = 0;
    private _graphs: any[] = [];
    private _riskLevels: any[] = [];
    private _levelData: any = {
        bullet: this.chartData
    };

    @Input() chartID: string;
    @Input() showRiskLevels: boolean;
    @Input() companyRiskLevel: any; //cluster code
    @Input() set riskLevels(value: any[]) {
        if (value) {
            let levelGraphs: any[] = [];
            let maxInterval = 0;
            for (var i = 0; i < value.length; i++) {
                levelGraphs.push({
                    fillAlphas: 1,
                    showBalloon: false,
                    type: "column",
                    lineColor: value[i].color,
                    valueField: value[i].shortName,
                    code: value[i].code
                });

                if (i == 0)
                    this._levelData[value[i].shortName] = value[i].topInterval;
                else
                    this._levelData[value[i].shortName] = value[i].topInterval - value[i - 1].topInterval;

                maxInterval = Math.max(maxInterval, value[i].topInterval);
            }

            this._graphs = levelGraphs.concat([
                {
                    fillAlphas: 1,
                    showBalloon: false,
                    type: "column",
                    valueField: "bullet",
                    lineColor: '#000000',
                    lineThickness: 1
                },
                {
                    clustered: false,
                    columnWidth: 0.3,
                    fillAlphas: 1,
                    lineColor: "#000000",
                    stackable: false,
                    type: "column",
                    valueField: "bullet"
                }, {
                    columnWidth: 0.6,
                    lineColor: "#000000",
                    lineThickness: 3,
                    noStepRisers: true,
                    stackable: false,
                    type: "step",
                    valueField: "limit"
                }
            ]);

            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.graphs = this._graphs
                    this.chart.valueAxes[0].maximum = maxInterval;
                });
            }
        }
        this._riskLevels = value;
        if (this.chart && this.showRiskLevels && this._riskLevels) {
            this.buildAxis(this.chart.categoryAxis.x);
        }
    }
    @Input() set chartData(value: number) {
        if (value) {
            this._levelData.bullet = value.toFixed(1);

            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = [this._levelData];
                });
            }
        }
        this._chartData = value;
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService) { }

    ngOnInit() {
        //prepare chart using the input risk levels
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "serial",
            autoMargins: false,
            marginTop: 12,
            marginLeft: 10,
            marginBottom: 25,
            marginRight: 40,
            dataProvider: [this._levelData],
            valueAxes: [{
                autoGridCount: false,
                stackType: "regular",
                gridAlpha: 0,
                axisThickness: 1,
                labelFunction: function (value, valueText, valueAxis) {
                    return valueText;
                },
                maximum: Math.max.apply(Math, this._riskLevels.map(function (item) { return item.topInterval; }))
            }],
            startDuration: 0, //animation disabled because of angular2-ie9-shims making it slow
            graphs: this._graphs,
            rotate: true,
            columnWidth: 1,
            categoryField: "category",
            categoryAxis: {
                gridAlpha: 0,
                position: "left",
                axisThickness: 1,
                tickLength: 0,
                axisColor: 'black',
                labelsEnabled: false
            },
            listeners: [{
                event: "rendered",
                method: (e) => {
                    if (this.chart == undefined) this.chart = e.chart;
                    if (this.showRiskLevels && this._riskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            },
            {
                event: "resized",
                method: (e) => {
                    if (this.showRiskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            }]
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }

    private buildAxis(startLocation: number): void {
        if (this.chart.valueAxes.length == 0 || this.chart.valueAxes[0].data == undefined) return;

        var minInterval = 0;
        var htmlContent = '', style = '', textStyle = '', distributionTextDiv = '';
        var element = document.createElement('canvas');
        var context = element.getContext("2d");
        context.font = "14px Calibri";

        //#FML
        var graphs = this.chart.valueAxes[0].data[0].axes[this.chart.valueAxes[0].id].graphs;
        var graphElements = Object.keys(graphs);

        Object.keys(graphs).forEach(element => {
            if (graphs[element].graph.type == 'column' && graphs[element].graph.valueField != 'bullet') {
                style = 'float: left;height: 100%;';
                textStyle = 'text-align: center;font-size: 8pt;margin:0px;';

                if (graphs[element].graph.code == this.companyRiskLevel)
                    style += 'font-weight: 900;';

                if (graphs[element].values.open == 0)
                    style += 'margin-left:' + startLocation + 'px; border-left: 1px dashed black;';

                style += 'border-right: 1px dashed black;width:' + graphs[element].columnWidth + 'px;';

                let text = graphs[element].graph.valueField;
                text = (text === 'Negligible' ? 'Negl' : text);

                distributionTextDiv = `<p class="text-center chart-legend" style="${textStyle}">${text}</p>`;

                htmlContent += "<div style='" + style + "'>" + distributionTextDiv + "</div>";
            }
        }, this);

        this.el.nativeElement.children.bulletChartAxis.innerHTML = htmlContent;
    }
}